package com.roc.web.action.merinfo;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.roc.bean.MerinfoSearchBean;
import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Operators;
import com.roc.pojo.TblMchtBizFee;
import com.roc.pojo.TblMchtInf;
import com.roc.service.IMerchantServices;
import com.roc.service.ServiceException;
import com.roc.service.operator.IPowerInfoService;
import com.roc.util.Constance;
import com.roc.util.constant.ConfigMerinfoUtil;
import com.roc.util.constant.Constant;
import com.roc.util.constant.MerinfoStatus;
import com.roc.util.constant.Role;

@Component
@Namespace("/merinfoysb")
@SuppressWarnings("all")
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class merinfoysbAction extends PaginationBaseAction {
	private static Logger logger = Logger.getLogger(merinfoysbAction.class);
	
	private MerinfoysbSearchCondition merysbSearchCondition;
	
	private Operators op;
	
	@Autowired
	IPageService pageService;
	
	@Autowired
	private IPowerInfoService powerInfoService;
	
	@Autowired
	private IMerchantServices merinfoService;
	
	private TblMchtInf merinfo; 
	
	private MerinfoSearchBean merinfoSearchBean;
	
	private List<TblMchtBizFee> mchtBizFees;
	
	private String directAgentId; //商户直属代理商
	
	private String merchantsNo; //商户号
	
	private String superRole; //角色转换
	
	private String merPhoneNo; //商户手机号
	

	@Action(value = "merysbListInit", results = {	
			@Result(name =SUCCESS, location = "/pages/merinfo/merinfoysbList.jsp"),
			@Result(name = ERROR, location = "/error.jsp") })
	public String merysbListInit(){
		try {
			op = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
			Map<String, String> map=powerInfoService.queryRealIdByOpId(op.getSuperiorId(), op.getRoleType(), op.getId(), op.getOrgCode());
			superRole= map.get("superRole");
			getRequest().setAttribute("roleType", superRole);
			return SUCCESS;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			e.printStackTrace();
			addActionError(e.getMessage());
			return ERROR;
		}
	}
	
	@Action(value = "merysbList", 
			results = { @Result(name = SUCCESS, location = "/pages/merinfo/merinfoysbList.jsp"),
			@Result(name = ERROR, location = "/error.jsp")
	})
	public String merysbList(){
		op = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		try {
			Map<String, String> map=powerInfoService.queryRealIdByOpId(op.getSuperiorId(), op.getRoleType(), op.getId(), op.getOrgCode());
			String orgCode=map.get("orgCode");
			String opRealId =map.get("opRealId");
			superRole= map.get("superRole");
			if((Role.SYSTEM.getCode().equals(superRole) || Role.O_MANAGER.getCode().equals(superRole)
					|| Role.AGENT.getCode().equals(superRole) || Role.MARKET_DIRECT.getCode().equals(op.getRoleType())
					|| Role.MARKET_LEAD.getCode().equals(op.getRoleType())) && !(Role.OPERATORS_LEAD.getCode().equals(op.getRoleType())
					|| Role.MERCHANT.getCode().equals(op.getRoleType()) || Role.AGENT_BUSS.getCode().equals(op.getRoleType())
					|| Role.SFB_AGENT.getCode().equals(op.getRoleType()))){
				if (merysbSearchCondition == null) {
					merysbSearchCondition = (MerinfoysbSearchCondition) getSearchConditionFromSession();
					if (merysbSearchCondition == null) {
						merysbSearchCondition = new MerinfoysbSearchCondition();
					}
				}
				merysbSearchCondition.setOrgCode(orgCode);
				merysbSearchCondition.setRoleType(op.getRoleType());
				merysbSearchCondition.setOprId(String.valueOf(op.getId()));
				merysbSearchCondition.setSupRoleType(superRole);
				merysbSearchCondition.setSupOprId(opRealId);
				handleResultList(op);
			}else{
				addActionError("无权限访问");
				return SUCCESS;	
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			addActionError(e.getMessage());
			return ERROR;
		}
		return SUCCESS;
	}
	
	public void handleResultList(Operators op) throws Exception{
		try {
			int rows = pageService.countSQL(merysbSearchCondition);
			List<MerinfoSearchBean> msList = new ArrayList<MerinfoSearchBean>();
			if(rows > 0){
				searchRsList = pageService.findAllSQL(merysbSearchCondition, calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
				if(searchRsList.size() > 0 && searchRsList != null){
					msList = handleMerinfoDetail(searchRsList, op);
				}
			}
			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute("COUNT", rows);//统计次数
			getRequest().setAttribute(SEARCH_RS_LIST, msList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			getRequest().setAttribute("roleType", superRole);
			getRequest().setAttribute("nowRoleType", op.getRoleType());
			setSearchToConditionSession(merysbSearchCondition);
		} catch (ServiceException e) {
			e.printStackTrace();
		}
	}
	
	public List<MerinfoSearchBean> handleMerinfoDetail(List<Object> objList, Operators op) throws Exception{
		List<MerinfoSearchBean> mList = new ArrayList<MerinfoSearchBean>();
		try {
				Iterator iterator = objList.iterator();
				while(iterator.hasNext()){
					Object[] obj = (Object[]) iterator.next();
					MerinfoSearchBean msb = new MerinfoSearchBean();
					msb.setMid(Constance.Null2EmptyTrim(obj[0]));
					msb.setMerName(Constance.Null2EmptyTrim(obj[1]));
					msb.setNationCd(Constance.Null2EmptyTrim(obj[2]));
					msb.setMerKind(Constance.Null2EmptyTrim(obj[3]));
					String status = Constance.Null2EmptyTrim(obj[4]);
					String statusr = "";
					if(status.length()>0){
						statusr = MerinfoStatus.getName(status);
					}
					msb.setFlag(statusr);//状态
					msb.setPerName(Constance.Null2EmptyTrim(obj[5]));
					String phone = Constance.Null2EmptyTrim(obj[6]);
					if(null != phone && phone.length() > 4){
						phone = phone.substring(0, 3)+"****"+phone.substring(phone.length()-4);
					}
					msb.setPerPhone(phone);
					msb.setInterContact(Constance.Null2EmptyTrim(obj[7]));
					String cardNo = Constance.Null2EmptyTrim(obj[8]);
					if(null != cardNo && cardNo.length() > 4){
						cardNo = cardNo.substring(0,3)+"****"+cardNo.substring(cardNo.length()-4);
					}
					msb.setCardNo(cardNo);
					msb.setRsvl(Constance.Null2EmptyTrim(obj[9]));
					msb.setRsvl3(Constance.Null2EmptyTrim(obj[10]));
					msb.setAmount1(Constance.Null2EmptyTrim(obj[11]));
					msb.setAmount2(Constance.Null2EmptyTrim(obj[12]));
					msb.setAgentId(Constance.Null2EmptyTrim(obj[13]));
					msb.setCompanyName(Constance.Null2EmptyTrim(obj[14]));
					msb.setExtId(Constance.Null2EmptyTrim(obj[15]));
					msb.setApplDate(Constance.Null2EmptyTrim(obj[16])); //入网时间
					String[] cycleList={"",""};
					cycleList[0]=Constance.Null2EmptyTrim(obj[17]);
					if(null!=Constance.Null2EmptyTrim(obj[18]) && !Constance.Null2EmptyTrim(obj[18]).equals("")){
						String j="";
						if(null!=cycleList[0] && !cycleList[0].equals("")){
							j="+";
						}
						cycleList[1]=j+Constance.Null2EmptyTrim(obj[18]);
					}
					msb.setMerCycle(cycleList);
					mList.add(msb);
				}
	} catch (Exception e) {
		logger.error(e.getMessage(),e);
		throw new Exception("查询失败",e);
	}
	return mList;
	}
	
	//云商宝会员费率初始化页面
	@Action(value = "queryYsbMchtFeeDetail", 
			results = { @Result(name = SUCCESS, location = "/pages/merinfo/editYsbMchtFee.jsp"),
			@Result(name = ERROR, location = "/error.jsp") })
	public String queryYsbMchtFeeDetail(){
		op = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		try {
			String extId = directAgentId;
			if(!op.getRoleType().equals(Role.OPERATORS_COMM.getCode())){
				if(!String.valueOf(op.getId()).equals(extId)){ //直属代理商才会有权限修改
					addActionMessage("当前登录人无此权限！");
					return ERROR;
				}
			}
			
				mchtBizFees = merinfoService.queryYsbMchtBizFeeList(merchantsNo);
				merinfo = merinfoService.queryMerchat(merchantsNo);
				getRequest().setAttribute("mcht_no", merchantsNo);
				getRequest().setAttribute(SEARCH_RS_LIST, mchtBizFees);
				getRequest().setAttribute("roleType", op.getRoleType());
			} catch (ServiceException e) {
				logger.error(e.getMessage(), e);
				addActionError(e.getMessage());
			}
			return SUCCESS;
	}
	
	//云商宝会员变更费率提交
	@Action(value = "editYsbMchtFees", 
			results = { @Result(name =SUCCESS, type = "chain", location = "merysbListInit"),
			@Result(name = ERROR, location = "/error.jsp") })
	public String editYsbMchtFees(){
		try {
			op = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
			String rtnInfo = merinfoService.editYsbMchtFeeInfo(mchtBizFees, op, merinfo);
			addActionMessage(rtnInfo);
		} catch (ServiceException e) {
			logger.error(e.getMessage(), e);
			addActionError(e.getMessage());
		}
		return SUCCESS;
	}
	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass() throws Exception {
		return merysbSearchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(merysbSearchCondition);
	}

	@Override
	protected void setSearchToConditionSession(BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_MERYSBINFO_INFO, merysbSearchCondition);

	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		return (MerinfoysbSearchCondition) getSession().getAttribute(SEARCH_SESSION_MERYSBINFO_INFO);
	}

	@Override
	protected String getInitPageSize() {
		return Constance.PAGE_MAX_SIZE + "";
	}

	public MerinfoysbSearchCondition getMerysbSearchCondition() {
		return merysbSearchCondition;
	}

	public void setMerysbSearchCondition(MerinfoysbSearchCondition merysbSearchCondition) {
		this.merysbSearchCondition = merysbSearchCondition;
	}

	public Operators getOp() {
		return op;
	}

	public void setOp(Operators op) {
		this.op = op;
	}

	public TblMchtInf getMerinfo() {
		return merinfo;
	}

	public void setMerinfo(TblMchtInf merinfo) {
		this.merinfo = merinfo;
	}

	public MerinfoSearchBean getMerinfoSearchBean() {
		return merinfoSearchBean;
	}

	public void setMerinfoSearchBean(MerinfoSearchBean merinfoSearchBean) {
		this.merinfoSearchBean = merinfoSearchBean;
	}

	public List<TblMchtBizFee> getMchtBizFees() {
		return mchtBizFees;
	}

	public void setMchtBizFees(List<TblMchtBizFee> mchtBizFees) {
		this.mchtBizFees = mchtBizFees;
	}

	public String getDirectAgentId() {
		return directAgentId;
	}

	public void setDirectAgentId(String directAgentId) {
		this.directAgentId = directAgentId;
	}

	public String getMerchantsNo() {
		return merchantsNo;
	}

	public void setMerchantsNo(String merchantsNo) {
		this.merchantsNo = merchantsNo;
	}

	public String getSuperRole() {
		return superRole;
	}

	public void setSuperRole(String superRole) {
		this.superRole = superRole;
	}

	public String getMerPhoneNo() {
		return merPhoneNo;
	}

	public void setMerPhoneNo(String merPhoneNo) {
		this.merPhoneNo = merPhoneNo;
	}

}
